<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>路由守卫</title>
    <script src="/js/js/vue.js"></script>
    <script src="/js/js/vue-router_3.0.2.js"></script>
</head>
<body>
    <div id="app">
        <router-view></router-view>
    </div>
    <script>
        // 组件
        var zhuye={
            template:`<div>
                <h1>主页内容</h1>
                </div>`
        }
         
        var login={
            template:`<div>
                <h1>登录页</h1>
                <input type='text'>
                <button @click='gologin'>登录</button>
                </div>`,
                methods:{
                    gologin(){
                        // 本地存储数据
                        // localStorage.setItem('uname','asuka');
                        // localStorage.setItem('age',28);
                        // let obj={
                        //     name:'tom',
                        //     age:89
                        // }
                        // json数据转字符串
                        // var jsonStr = JSON.stringify(obj);
                        // localStorage.setItem('liuu',jsonStr);
                        // localStorage.clear();

                        // let v=localStorage.getItem('liuu');
                        // let obj=JSON.parse(v);
                        // console.log(obj.name);

                        //登陆标志
                        localStorage.setItem('token','ssssffff');
                        
                    }
                }
        }
       
        // 嵌套路由配置
        var router = new VueRouter({
            routes:[
                {path:'/login',component:login},
                {path:'/zhuye',component:zhuye}
            ]
        })

        //守卫
        router.beforeEach((to, from, next) => {
            console.log('守卫', to);
            let token=localStorage.getItem('token');
            if(to.path =='/login' || token){
                next();//放行
            }else{
                next('/login')
            }

            // 放行
            // next();
        });
        
        // Vue实例
        var vm = new Vue({
            el:'#app',
            data:{},
            router: router // 挂载路由
        })
       
    </script>
</body>
</html>